var rp = require('request-promise');
//var rePost = require('body-parser');
var reFilter = require('./filter');
var functionParas={queryLocator,queryFind,queryQuery,queryLocators,queryDistance,queryBuffer};
//单字段地理编码
function queryLocator(layerName, queryName) {
	var qs = {
		//SingleKey:queryName,
		SingleKey: queryName,
		outFields: ["Name,Address"],
		f: "json"
	}
	var strName = layerName + "_CreateAddressLocator";
	var options = {
		url: 'http://222.73.156.99:6080/arcgis/rest/services/' + strName + '/GeocodeServer/findAddressCandidates',
		qs: qs,
		json: true // Automatically parses the JSON string in the response 
	};
	return rp(options)
		.then(function (repos) {
			console.log("请求成功", repos);
			return repos;
		});
}
//多字段地理编码，模糊匹配
function queryLocators(layerName, queryNames) {

	var strName = layerName + "_CreateAddressLocator";

	return queryNames.reduce(function (previous, current) {
		return previous.then(function (data) {
			return rp({
				url: 'http://222.73.156.99:6080/arcgis/rest/services/' + strName + '/GeocodeServer/findAddressCandidates',
				qs: {
					SingleKey: current,
					outFields: ["Name,Address"],
					f: "json"
				},
				json: true
			}).then(function (body) {
				var newData = reFilter.dataFilter(body.candidates);
				return data.concat(newData);
			});
		});
	}, Promise.resolve([]));
}

//查询Find，返回外轮廓经纬度
function queryFind(layerName, queryNames) {
	var num;
	var geoType;
	switch (layerName) {
		case "JZXH":
			num = 6;
			geoType = "polygon";
			break;
		case "DL":
			num = 2;
			geoType = "line";
			break;
		case "GS":
			num = 3;
			geoType = "polygon";
			break;
	}
	return queryNames.reduce(function (previous, current) {
		return previous.then(function (data) {
			return rp({
				url: 'http://222.73.156.99:6080/arcgis/rest/services/SongJiangMap/MapServer/find',
				qs: {
					searchText: current,
					contains: true,
					//searchFields:Name,
					layers: num,
					returnGeometry: true,
					f: "json"
				},
				json: true
			}).then(function (body) {
				var newData;
				if (geoType == "line") {
					newData = reFilter.pathsFilter(body.results);
				} else {
					newData = reFilter.ringsFilter(body.results);
				}
				return data.concat(newData);
			});
		});
	}, Promise.resolve([]));

	/*var qs={
		searchText:queryName,
		contains:true,
		//searchFields:Name,
		layers:num,
		returnGeometry:true,
		f:"json"
	}
	var options={
		url:'http://222.73.156.99:6080/arcgis/rest/services/SongJiangMap/MapServer/find',
		qs:qs,
		json:true
	} 
	return rp(options)
	.then(function(repos) {
		console.log("请求成功",repos);
		return repos;
	});*/
}

//query查询名称
function queryQuery(layerName) {
	var num;
	switch (layerName) {
		//建筑细化
		case "JZXH":
			num = 6;
			break;
		//一般道路
		case "DL":
			num = 2;
			break;
		//高速
		case "GS":
			num = 3;
			break;
		//变电站
		case "BDZ":
			num = 0;
			break;
		//河道
		case "HD":
			num = 8;
			break;
		//桥梁
		case "QL":
			num = 1;
			break;
	}
	var qs = {
		where: "name=name",
		//geometryType:esriGeometryEnvelope,
		outFields: "Name",
		returnGeometry: false,
		returnIdsOnly: false,
		returnZ: false,
		returnDistinctValues: true,
		f: "json"
	}
	var options = {
		url: 'http://222.73.156.99:6080/arcgis/rest/services/SongJiangMap/MapServer/' + num + '/query',
		qs: qs,
		json: true
	}
	return rp(options)
		.then(function (repos) {
			console.log("请求成功", repos);
			return repos;
		});

}

//计算距离
function queryDistance(geos) {
	//由于request-promise的上级库request里的qs序列化的结果，与
	//ArcGIS REST API中要求的URL不一致，故直接输入JSON格式到qs中，先用JSON.stringify()先序列化。
	geo1 = JSON.stringify(geos.geo1);
	geo2 = JSON.stringify(geos.geo2);
	var qs = {
		sr: 4326,
		geometry1: geo1,
		geometry2: geo2,
		geodesic: true,
		distanceUnit: 9001,//??查官方手册,9001：米;9035:英里
		f: "json"
	}
	var options = {
		url: 'http://222.73.156.99:6080/arcgis/rest/services/Utilities/Geometry/GeometryServer/distance',
		qs: qs,
		json: true
	}
	return rp(options)
		.then(function (repos) {
			console.log("请求成功", repos);
			return repos;
		});
}
//缓冲区
function queryBuffer(query) {
	var qs1 = {
		searchText: query.queryName,
		contains: true,
		searchFields:"Name",
		layers: "2",
		returnGeometry: true,
		f: "json"
	}
	var options1 = {
		url: 'http://222.73.156.99:6080/arcgis/rest/services/SongJiangMap/MapServer/find',
		qs: qs1,
		json: true
	}
	return rp(options1)
		.then(function (repos) {
			//序列化缓冲区查询的geometry对象
			var geo = JSON.stringify(reFilter.createBufGeo(repos));
			//var geometry = reFilter.dataFilter(repos.geometry);
			var qs2 = {
				geometries: geo,
				inSR: 4326,
				outSR: 4326,
				bufferSR: 102113,//WGS_1984_Web_Mercator
				distances: query.distance,
				unionResults: false,
				f:"json"
			}
			var options2 = {
				uri: 'http://222.73.156.99:6080/arcgis/rest/services/Utilities/Geometry/GeometryServer/buffer',
				qs: qs2,
				json: true
			}
			return rp(options2)
				.then(function (resp) {
					//序列化Identify的Geometry对象
					var geo=JSON.stringify(reFilter.createIdenGeo(resp));
					//indentify 请求参数
					var qs3 = {
						geometryType:"esriGeometryPolygon",
						geometry:geo,
						sr:4326,
						layers:"all:6",
						tolerance:5,
						mapExtent:"121.142443,30.989724,121.173988,31.033077",//地图范围，必填
						imageDisplay:"400,300,96",//图像显示范围，必填
						f:"json"
					}
					var options3 = {
						uri:"http://222.73.156.99:6080/arcgis/rest/services/SongJiangMap/MapServer/identify",
						qs:qs3,
						json:true
					}
					return rp(options3)
						.then(function (repos) {
							//新加
							console.log("请求成功", repos);
							return repos;
						});
				});
		});
}
module.exports =functionParas;//暴露函数